package com.icu.config;

import cn.dev33.satoken.context.SaHolder;
import cn.dev33.satoken.filter.SaServletFilter;
import cn.dev33.satoken.jwt.StpLogicJwtForStateless;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.json.JSONUtil;
import com.icu.enums.ErrorEnum;
import com.icu.util.RUtil;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Sa-Token
 */
@Configuration
public class SaTokenConfig {

    /**
     * Stateless 模式：服务器完全无状态
     */
    @Bean
    public StpLogic getStpLogicJwt() {
        return new StpLogicJwtForStateless();
    }

    /**
     * 注册 [Sa-Token全局过滤器]
     */
    @Bean
    public SaServletFilter getSaServletFilter() {
        return new SaServletFilter()
                .addInclude("/**")
                .addExclude("/user/login", "/user/add")
                .setAuth(obj -> SaRouter
                        .match("/**", StpUtil::checkLogin)
                )
                .setError(e -> JSONUtil.toJsonStr(RUtil.errorEnum(ErrorEnum.USER_TOKEN_EXPIRED))
                )
                .setBeforeAuth(r -> SaHolder
                        .getResponse()
                        .setHeader("X-Frame-Options", "SAMEORIGIN")
                        .setHeader("X-XSS-Protection", "1; mode=block")
                        .setHeader("X-Content-Type-Options", "nosniff")
                );
    }


}
